import React, { useState, useEffect } from "react";
import { createBrowserRouter, RouterProvider,createHashRouter } from "react-router";
import { routesMobile, routesComputer } from "./router/index";

// 定义设备类型检测函数
const getDeviceTypeByScreenSize = () => {
  const width = window.innerWidth;

  if (width <= 767) {
    return "Mobile"; // 手机设备
  } else if (width >= 768 && width <= 1024) {
    return "Tablet"; // 平板设备
  } else {
    return "Pc"; // 桌面设备
  }
};

function App() {
  const [deviceType, setDeviceType] = useState(getDeviceTypeByScreenSize()); // 初始化设备类型

  useEffect(() => {
    const handleResize = () => {
      const newDeviceType = getDeviceTypeByScreenSize();
      if (newDeviceType !== deviceType) {
        setDeviceType(newDeviceType); // 更新设备类型
      }
    };

    const setRootFontSize = () => {
      console.log('设计稿宽度');
      const designWidth = 750; // 设计稿宽度
      const clientWidth =
        document.documentElement.clientWidth || window.innerWidth;
      const fontSize = (clientWidth / designWidth); // 动态计算根字体大小
      document.documentElement.style.fontSize = `${fontSize}px`;
      console.log('fontSize',fontSize);
    };

    const initPages = () => {
      handleResize();
      setRootFontSize();
    };

    setRootFontSize();

    window.addEventListener("resize", initPages); // 添加窗口大小监听器

    return () => {
      window.removeEventListener("resize", initPages); // 清理监听器
    };
  }, [deviceType]); // 监听 deviceType 变化

  // 根据设备类型选择路由
  const routes = deviceType === "Pc" ? routesComputer : routesMobile;
  const router = createHashRouter(routes);

  return <RouterProvider router={router} />;
}

export default App;
